﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using WebApiMIT3.BusinessLayer;
using WebApiMIT3.DatabaseAccessLayer;
using WebApiMIT3.Models;


namespace WebApiMIT3.Controllers
{
    // <Author>Rainer Schmitt</Author>
    // <StudentNo>1235656</StudentNo>
    // Copyright (c) 06/04/2015 All Right Reserved
    // <Date>06/04/2015</date>
    public class DataTrafficController : ApiController
    {
        private const string AppDataPath = "~/App_Data";
        private DataManager dataManager = new DataManager();

        /// <summary>
        /// Adds the data to the webapi from the webcrawler.
        /// </summary>
        /// <returns>HttpResponseMessage</returns>
        [HttpPost]
        [ActionName("PostNews")]
        public async Task<HttpResponseMessage> PostNews()
        {
            
            var path = HttpContext.Current.ApplicationInstance.Server.MapPath(AppDataPath);

            if (!Directory.Exists(path))
            {
                Directory.GetDirectories(path);
            }

            await DataTrafficHelper.DeleteAllFilesInDir(path);

            // Check if the request contains multipart/form-data.
            if (!Request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }

            string root = HttpContext.Current.Server.MapPath(AppDataPath);
            var provider = new MultipartFormDataStreamProvider(root);

            try
            {
                // Read the form data.
                await Request.Content.ReadAsMultipartAsync(provider);

                // This illustrates how to get the file names.
                foreach (MultipartFileData file in provider.FileData)
                {
                    Trace.WriteLine(file.Headers.ContentDisposition.FileName);
                    Trace.WriteLine("Server file path: " + file.LocalFileName);
                }
            }
            catch (Exception e)
            {
                return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
            }

            await this.dataManager.PostNews(path);

            return Request.CreateResponse(HttpStatusCode.OK);
        }

        /// <summary>
        /// Gets the data from the database to give it to the client.
        /// </summary>
        /// <param name="categoryList"></param>
        /// <returns>HttpResponseMessage</returns>
        [HttpGet]
        [ActionName("GetNews")]
        public async Task<HttpResponseMessage> GetNews([FromUri] string categoryList = null)
        {
            List<string> categories = await DataTrafficHelper.GetCategories(categoryList);
            string result = await this.dataManager.GetNews(categories);

            var response = new HttpResponseMessage();
            response.Content = new StringContent(result);
            response.StatusCode = HttpStatusCode.Accepted;

            return response;
        }
    }
}
